<?php


namespace common\behavior\CommonMessagePushing;

use common\model\NoteModel;
use common\model\StepCategoryModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\NoteService;
use common\service\ProjectService;
use Webman\Stomp\Client;

/**
 * 需求新评论 推送新消息通知
 */
class NoteNewCommentBehavior
{

    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'demand_type' => 'strval',
                'comment_subject_id' => 'intval',
                'text' => 'strval|mb_substr,{{text}},0,100',
                'project_id' => 'intval',
                'module_code' => 'strval',
                'tenant_id' => 'intval',
                'created_by' => 'intval',
                'created' => 'intval',
            ],
            [
                'demand_type' => '',
                'comment_subject_id' => 0,
                'text' => '',
                'project_id' => 0,
                'module_code' => '',
                'tenant_id' => 0,
                'created_by' => 0,
                'created' => 0,
            ],
            'data',
            ['type' => 'note_has_new_comment'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($demandType, $commentSubjectId, $text, $projectId, $moduleCode, $tenantId, $createdBy, $created) = $params;
        if ($demandType != 'comment' || empty($commentSubjectId)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/

        $commentUser = model(UserModel::class)->where(['id' => $createdBy])->find();
        $note = model(NoteModel::class)
            ->join('note_entity_relation on note_entity_relation.note_id = note.id', 'left')
            ->where(['note.id' => $commentSubjectId])
            ->field('note.*, note_entity_relation.step_category_id')
            ->find();
        if (empty($note)) {
            return;
        }

        $configStepCategoryIds = [];
        if (!empty($note['step_category_id'])) {
            $configStepCategoryIds = $note['step_category_id'];
        } else {
            $moduleId = module_by_code($note['module_code'])['id'];
            $configStepCategoryIds = model(StepCategoryModel::class)
                ->where([
                    'entity_id' => $moduleId,
                    'parent_id' => ['neq', 0],
                ])
                ->column('id');
            // 无环节的 查询需求关联实体类型
        }

        $unionIdList = NoteService::getInstance()->getDemandRelatePeople($note, false);
        // 抄送给该需求关联的环节 配置的【环节制片】
        $unionIdListCc = [];
        if (!empty($configStepCategoryIds)) {
            $unionIdListCc = ProjectService::getInstance()->projectConfigMessageReceiverUnionIdList([
                'project_id' => $note['project_id'],
                'step_category_id' => $configStepCategoryIds,
                'role_code_list' => ['step_producer'],
            ]);
        }
        $unionIdList = array_unique(array_merge($unionIdList, $unionIdListCc));

        $notifyParam = [
            'first' => "需求" . mb_substr($note['text'], 0, 15) . " 有新的评论",
            'remark' => "请及时查看",
            'comment_content' => $text,
            'comment_at' => date("Y/m/d H:i:s", $created),
            'comment_user_name' => $commentUser['name'],
            'tenant_id' => $tenantId,
            'demand_id' => $commentSubjectId,
            'project_id' => $projectId,
            'module_code' => $moduleCode,
            'message_key' => 'demand_has_new_comment',
        ];
        $templateId = NoteService::getInstance()->getDemandCommentAddTemplateId();
        $messageGenerated = [];
        foreach ($unionIdList as $unionId) {
            if ($unionId == $commentUser['union_id']) {
                continue;
            }
            $messageGenerated[] = [
                "param" => $notifyParam,
                'receiver' => $unionId,
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'message_demand',
                'is_popup' => 1,
                'message_key' => 'demand_has_new_comment',
                'project_id' => $note['project_id'],
            ];
        }
        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
